<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNew ? '新建数据权限' : '修改数据权限'"
    width="600px"
    :before-close="close"
  >
    <div v-loading="loading">
      <el-form ref="formRef" :model="formData" label-width="120" :rules="rules">
        <el-form-item label="名称：" prop="name">
          <el-input
            v-model="formData.name"
            :disabled="!isNew && formData.businessName === 'unitId'"
          />
        </el-form-item>
        <el-form-item label="数据字段：" prop="businessName">
          <dictionary-select
            v-model="formData.businessName"
            parent-dictionary-value="dataPermissionBusinessName"
          />
        </el-form-item>
        <el-form-item label="标识符：" prop="code">
          <el-input
            v-model="formData.code"
            :disabled="!formData.businessName"
            :placeholder="!formData.businessName ? '请先选择数据字段' : ''"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            :max="999"
            :min="1"
            :precision="0"
          />
        </el-form-item>
        <el-form-item label="所属单位：" prop="unitId">
          <unit-select
            v-model="formData.unitId"
            :permission="addPermission"
            placeholder="请选择组织单位"
          />
        </el-form-item>
        <el-text tag="div" style="padding-left: 125px; line-height: 1.5">
          <div style="padding-bottom: 10px">
            数据字段为组织单位字段时，请输入对应组织单位编号。
          </div>
          <div>数据字段为领导字段时，不能用纯数字作为标识符。</div>
        </el-text>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, useTemplateRef } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import DictionarySelect from '@/components/dictionary/DictionarySelect.vue'
import UnitSelect from '@/components/unit/UnitSelect.vue'
import { addOrUpdateDataPermission } from '@/api/sys/dataPermission'
import { Message } from '@/hooks/message'

const addPermission = 'dataPermission:add'

const formRef = useTemplateRef<FormInstance>('formRef')
const emit = defineEmits(['update'])

const dialogVisible = ref(false)
const isNew = ref(true)
const loading = ref(false)

const formData = reactive({
  id: undefined,
  name: undefined,
  code: undefined,
  sort: 50,
  type: undefined,
  unitId: undefined,
  businessName: undefined,
})

const rules = reactive<FormRules<typeof formData>>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入标识符', trigger: 'blur' },
    { validator: checkCode, trigger: 'blur' },
  ],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  type: [{ required: true, message: '请选择终端类型', trigger: 'change' }],
  unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
  businessName: [
    { required: true, message: '请选择数据字段', trigger: 'blur' },
  ],
})

defineExpose({ show })

function checkCode(rule: any, value: any, callback: any) {
  if (formData.businessName === 'unitId') {
    if (!Number(value)) {
      callback(new Error('数据字段为组织单位字段时，请输入对应组织单位编号。'))
      return
    }
  } else if (formData.businessName === 'leaderId') {
    if (Number(value)) {
      callback(new Error('数据字段为领导字段时，不能用纯数字作为标识符。'))
      return
    }
  }
  callback()
}

async function show(row?: any) {
  dialogVisible.value = true
  if (row) {
    formData.id = row.id
    formData.name = row.name
    formData.code = row.code
    formData.sort = row.sort
    formData.type = row.type
    formData.unitId = row.unitId
    formData.businessName = row.businessName
    isNew.value = false
  }
}

function close() {
  dialogVisible.value = false
  isNew.value = true
  loading.value = false
  formRef.value.resetFields()
  Object.assign(formData, {
    id: undefined,
    name: undefined,
    code: undefined,
    sort: 50,
    type: undefined,
    unitId: undefined,
    businessName: undefined,
  })
}

async function submit() {
  const bool = await formRef.value.validate()
  if (!bool) {
    return
  }
  loading.value = true
  const { data } = await addOrUpdateDataPermission(formData)
  if (data.status === 200) {
    Message({
      message: data.message,
      type: 'success',
    })
  }
  emit('update')
  close()
}
</script>
<style scoped lang="scss"></style>
